package kr.couponplay.android.domain;

import java.util.ArrayList;
import java.util.List;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.Category;
import kr.couponplay.android.ServiceInfo;
import kr.couponplay.android.domain.ButtonView.MenuType;
import kr.couponplay.android.util.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class DealDao {
	public static final String SEARCH_URL = "http://couponplay.kr/api/search.json";
	public static final String MAIN_DEAL_URL = "http://couponplay.kr/api/mainDeals.json";
	public static final String MY_RECENT_VIEW_DEAL_URL = "http://couponplay.kr/api/my/recentViewDeals.json";
	public static final String MY_RECENT_QUERIES_URL = "http://couponplay.kr/api/my/recentQueries.json";
	public static final String CATEGORY_URL = "http://couponplay.kr/api/categories.json";
	public static final String SERVICE_INFO_URL = "http://couponplay.kr/api/serviceInfo.json";

	public DealList findAll(String menuType) {
		if (MenuType.RECENT.name().equals(menuType)) {
			return getRecentViewDeals();
		}
		return search();
	}
	
	public DealList search() {
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("?page=" + String.valueOf(AppContext.getPage()));
			sb.append("&query=" + AppContext.query);
			sb.append("&order=" + AppContext.getSortingType());
			sb.append("&mainMenuId=" + AppContext.mainMenuId);
			sb.append("&subMenuId=" + AppContext.subMenuId);
			sb.append("&itemCountInPage=" + AppContext.itemCountInPage);
			sb.append("&sid=" + AppContext.sid);
			if (AppContext.searchType != null) {
				sb.append("&type=" + AppContext.searchType);
			}
	        
			String result = HttpUtils.execute(SEARCH_URL + sb.toString());
			
			JSONObject jsonCondition = new JSONObject(result).getJSONObject("condition");
			int totalItemCount = jsonCondition.getInt("totalItemCount");
			
			JSONObject jsonObject = new JSONObject(result).getJSONObject("searchDealViewList");
			JSONArray array = jsonObject.getJSONArray("deals");
			List<Deal> deals = makeDealList(array);
			return new DealList(deals, totalItemCount);
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
			throw new IllegalArgumentException();
		}
	}

	public ServiceInfo getServiceInfo() {
		try {
			String result = HttpUtils.execute(SERVICE_INFO_URL);
			DealList mainDealList = mainDealList(result);
			Category category = makeCategory(result);
			
			ServiceInfo serviceInfo = new ServiceInfo();
			serviceInfo.setMainDealList(mainDealList);
			serviceInfo.setCategory(category);
			return serviceInfo;
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
			throw new IllegalArgumentException();
		}
	}
	
	public DealList getRecentViewDeals() {
		DealList dealList = new DealList(new ArrayList<Deal>(), 0);
		if (AppContext.sid == null) {
			return dealList;
		}
		
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("?sid=" + AppContext.sid);
			String result = HttpUtils.execute(MY_RECENT_VIEW_DEAL_URL + sb.toString());
			
			JSONObject jsonObject = new JSONObject(result).getJSONObject("recentDealViewList");
			JSONArray array = jsonObject.getJSONArray("deals");
			List<Deal> deals = makeDealList(array);
			return new DealList(deals, deals.size());
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
			return dealList;
		}		
	}

	public List<RecentQuery> getRecentQueries(String result) {
		try {
	        if (result == null) {
	        	result = HttpUtils.execute(MY_RECENT_QUERIES_URL + "?sid=" + AppContext.sid);
	        }

	        JSONArray queryArray = new JSONObject(result).getJSONArray("recentQueries");
	        List<RecentQuery> queries = new ArrayList<RecentQuery>();
			for (int i = 0; i < queryArray.length(); i++) {
				JSONObject object = queryArray.getJSONObject(i);
				
				RecentQuery recentQuery = new RecentQuery();
				recentQuery.setSid(object.getString("sid"));
				recentQuery.setQuery(object.getString("query"));
				recentQuery.setInsertDate(object.getString("insertDate"));
				queries.add(recentQuery);
			}
	        return queries;
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
			throw new IllegalArgumentException();
		}
	}

	public Category makeCategory(String result) {
		try {
//	        if (result == null) {
//	        	result = HttpUtils.execute(CATEGORY_URL);
//	        }

			Category root = new Category();
			JSONArray groupArray = new JSONObject(result).getJSONArray("mainMenus");
			for (int i = 0; i < groupArray.length(); i++) {
				JSONObject object = groupArray.getJSONObject(i);
//				int mainGroupCount = object.getInt("dealCount");
				JSONObject groupObject = object.getJSONObject("category");
				Category group = new Category();
				group.setId(groupObject.getInt("id"));
				group.setName(groupObject.getString("name"));
				group.setLevelNo(groupObject.getInt("levelNo"));
				group.setOrderNo(groupObject.getInt("orderNo"));
				group.setParentId(groupObject.getInt("parentId"));
				
				JSONArray childArray = object.getJSONArray("subCategories");
				Category copy = group.copy();
				copy.setName(copy.getName() + " 전체");
				group.addChild(copy);
				for (int j = 0; j < childArray.length(); j++) {
					JSONObject childObject = childArray.getJSONObject(j);
					Category child = new Category();
					child.setId(childObject.getInt("id"));
					child.setName(childObject.getString("name"));
					child.setLevelNo(childObject.getInt("levelNo"));
					child.setOrderNo(childObject.getInt("orderNo"));
					child.setParentId(childObject.getInt("parentId"));
					group.addChild(child);
				}
				root.addChild(group);
			}
			return root;
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
			throw new IllegalArgumentException();
		}
	}

	public DealList mainDealList(String result) {
		try {
	        if (result == null) {
	        	result = HttpUtils.execute(MAIN_DEAL_URL);
	        }
			
			JSONObject jsonObject = new JSONObject(result).getJSONObject("mainDealViewList");
			JSONArray array = jsonObject.getJSONArray("deals");
			List<Deal> deals = makeDealList(array);
			return new DealList(deals, deals.size());
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
			throw new IllegalArgumentException();
		}
	}

	private List<Deal> makeDealList(JSONArray array) throws JSONException {
		List<Deal> deals = new ArrayList<Deal>();
		for (int i = 0; i < array.length(); i++) {
			JSONObject object = array.getJSONObject(i);
			Deal dealView = new Deal();
			dealView.setId(object.getInt("id"));
			dealView.setTitle(object.getString("title"));
			dealView.setMetaId(object.getString("metaId"));
			dealView.setDiscountRate(object.getInt("discountRate"));
			dealView.setNowCount(object.getInt("nowCount"));
			dealView.setProviderCode(ProviderCode.valueOf(object.getString("providerCode")));
			dealView.setOriginalPrice(object.getInt("originalPrice"));
			dealView.setSalesPrice(object.getInt("salesPrice"));
			dealView.setFromDate(object.getString("saleStartAt"));
			dealView.setToDate(object.getString("saleEndAt"));
			dealView.setThumbnailImageUrl1(object.getString("imageUrl"));
			dealView.setImageUrl1(object.getString("imageUrl1"));
			dealView.setDetailViewUrl(ProviderUtils.landingPage(dealView.getId(), dealView.getProviderCode(), dealView.getMetaId()));
			dealView.setViewDate(object.getString("viewDate"));
			deals.add(dealView);
		}
		return deals;
	}
}
